package edu.fpa.day0728;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

    public static void main(String[] args) {
        //1.文件-文件
        try {
            InputStream i = new FileInputStream("hello.txt");
            OutputStream o = new FileOutputStream("dest.txt");
            copy(i,o);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //2.文件-字节数组
        byte[] b = null;
        try {
            InputStream i = new FileInputStream("hello.txt");
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            copy(i,bo);
            b = bo.toByteArray();
            System.out.println(new String(b));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //3.字节数组-文件
        ByteArrayInputStream bi = new ByteArrayInputStream(b);
        try {
            OutputStream o = new FileOutputStream("dest.txt");
            copy(bi,o);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
    public static void copy(InputStream i,OutputStream o) {
        byte[] b = new byte[2];
        int len = -1;
        try {
            while((len=i.read(b))!=-1) {
                o.write(b, 0, len);
            }
            o.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            close();
        }

    }
    public static void close(Closeable...ios) {
        for(Closeable io:ios) {
            try {
                if(io!=null)
                    io.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
